package com.itheima.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //1.密码加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2.查询用户名是否存在
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //3.用户名不存在
        if (emp == null) {
            return R.error("用户名不存在");
        }

        //4.密码不匹配
        if (!emp.getPassword().equals(password)) {
            return R.error("密码不匹配");
        }

        //5.是否被禁用
        if (emp.getStatus() == 0) {
            return R.error("账号已禁用");
        }

        //6.登录成功，返回对象，设置session属性
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);


    }

    /**
     * 退出功能
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }


    @GetMapping("/export")
    public void R(HttpServletResponse response){
        try {
            response.setHeader("Content-Disposition",
                    "attachment;filename=employee.xlsx");
            List<Employee> list = employeeService.list();
            ServletOutputStream outputStream = response.getOutputStream();
            EasyExcel.write(outputStream,Employee.class).sheet("员工数据").doWrite(list);

            outputStream.close();
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    /**
     * 新增员工
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> saveemp( @RequestBody Employee employee,HttpServletRequest request) {

        log.info("新增员工，员工信息为：{}", employee.toString());

        //1.设置初始密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        Long empId = (Long) request.getSession().getAttribute("employee");

        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);

        employeeService.save(employee);
        return R.success("新增员工成功");

    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> pageR(int page,int pageSize,String name){
        log.info("page={},pagesize={},name={}",page,pageSize,name);

        //1.page
        Page pageinfo = new Page<>(page,pageSize);

        //2.lqw
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();

        //3.1 name
        lqw.like(StringUtils.isNotEmpty(name), Employee::getName,name);

        //3.2 desc
        lqw.orderByDesc(Employee::getUpdateTime);

        //4.do
        employeeService.page(pageinfo,lqw);

        return R.success(pageinfo);
    }

    /**
     * 保存员工信息
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> updateemp(@RequestBody Employee employee,HttpServletRequest request){
        log.info(employee.toString());

/*         Long empId=(Long) request.getSession().getAttribute("employee");
       employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(empId);*/
        employeeService.updateById(employee);

        return R.success("员工信息修改成功");
    }

    /**
     * 根据id查询员工信息，进行回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("id={}.........",id);
        Employee employee = employeeService.getById(id);
        if(employee!=null){
            return R.success(employee);

        }
        return R.error("非法员工，请退出后重新登录");
    }



}
